package com.qb.devserv;

import static com.qb.devserv.MainActivity.mActivity;
import static com.qb.devserv.MainService.mService;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.DevInfoUtil;
import utils.MyUtil;

public class FactoryActivity extends AppCompatActivity {

    Context ctx;
    public static FactoryActivity fActivity;
    Timer fActive;
    TextView tvBoardSN,tvBind;
    EditText etSN,etOrder;
    MiniLoadingDialog mMiniLoadingDialog;
    SharedPreferences SP;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        XUI.initTheme(this);
        XToast.Config.get().setGravity(Gravity.CENTER);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.setDialogSize(150,150);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_factory);
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = 840;
        lp.height = 560;
        this.getWindow().setAttributes(lp);
        ctx = FactoryActivity.this;
        fActivity = this;
        SP = getSharedPreferences("dev_mgt_setting", this.MODE_PRIVATE);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        etSN = findViewById(R.id.et_sn);
        etSN.requestFocus();
        TextView tvClear = findViewById(R.id.tv_clear);
        tvClear.setVisibility(View.GONE);
        tvClear.setOnClickListener(view -> {
            etSN.setText("");
            etSN.requestFocus();
        });
        etSN.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                MyUtil.showLog("etSN.addTextChangedListener",charSequence);
            }
            @Override
            public void afterTextChanged(Editable editable) {
                MyUtil.showLog("afterTextChanged",editable);
                if (editable.length() <= 0) {
                    tvClear.setVisibility(View.GONE);
                } else {
                    tvClear.setVisibility(View.VISIBLE);
                }
            }
        });
        etOrder = findViewById(R.id.et_order);
        etOrder.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (b) {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                } else {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 2);
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                }
            }
        });

        tvBoardSN = findViewById(R.id.tv_board_sn);
        tvBoardSN.setText(DevInfoUtil.getSN());

        tvBind = findViewById(R.id.tv_bind);
        tvBind.setOnClickListener(view -> {
            String sn = String.valueOf(etSN.getText()).trim();
            String bsn = String.valueOf(tvBoardSN.getText()).trim();
            String order = String.valueOf(etOrder.getText()).trim();
            if (MyUtil.isNull(sn)) {
                XToastUtils.warning("设备序列号不能为空", Toast.LENGTH_LONG);
            } else if (bsn.equals("unKnown")) {
                XToastUtils.warning("无效的主板序列号", Toast.LENGTH_LONG);
            } else {
                JSONObject p = new JSONObject();
                try {
                    // 绑定完成，禁止自动跳出绑定界面
                    mService.stopTask(fActive);
                    // 发送mqtt绑定信息
                    p.put("sn",sn);  // 设备序列号
                    p.put("borad_sn",bsn);  // 主板序列号
                    p.put("project_list_number",order);  //项目单编号
                    p.put("terminal_type","");  //终端类型，暂时没用
                    p.put("equipment_model_id","2749b36ab6043b44fd7122b65ae1939d77dsds25d");  //默认的设备类型，固定值
                    p.put("plat_user_id","5a8f8d23dfe7cf6a4d115b3448edd93sd346b727e72");  //默认的所属用户类型，固定值
                    mService.sendMsg("DEVICE_BIND",p);
                } catch (JSONException e) {
                    e.printStackTrace();
                    XToastUtils.error("绑定失败 "+e.getMessage(), Toast.LENGTH_LONG);
                }
            }

        });
        // 没完成绑定时，300秒弹出一次绑定窗口
        fActive = mService.rollTask("factory_activity", 300);
    }

    private void devCreateDone(JSONArray data) {
        MyUtil.showLog("***devCreateDone****", data);
        new Handler().postDelayed(()-> {
            startActivities(new Intent[]{new Intent().setClass(this, MainActivity.class)});
            finish();
        },1500);
    }

    /*
     * http
     * */
    public void httpAction(String flag,String url,String method,String postJson) {
        String BaseUrl = SP.getString("baseUrl","");
        if (BaseUrl.indexOf(".") < 10) {
            return;
        }
        url = BaseUrl+url;
        String token = SP.getString("token","");
        MyUtil.showLog("httpAction",flag);
        MyUtil.showLog("",url);
        MyUtil.showLog("",method);
        MyUtil.showLog("",postJson);
        MyUtil.showLog("token",token);
        if (method.equals("get")) mMiniLoadingDialog.updateMessage("数据加载中…");
        if (method.equals("post")) mMiniLoadingDialog.updateMessage("绑定中…");
        mMiniLoadingDialog.show();
        OkHttpClient ohc = new OkHttpClient();
        Request request = null;
        if (method.equals("get")) {
            request = new Request.Builder().url(url)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        if (method.equals("post")) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
            request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        ohc.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                MyUtil.showLog("httpAction onFailure",e.getMessage());
                runOnUiThread(() -> {
                    mMiniLoadingDialog.dismiss();
                    XToastUtils.error("网络连接失败 "+e.getMessage(), Toast.LENGTH_LONG);
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                successResult(response, flag);
            }
        });
    }
    public void successResult(Response res, String flag) {
        runOnUiThread(() -> {
            mMiniLoadingDialog.dismiss();
        });
        if (res.code() == 200) {
            try {
                String r = "{}";
                try {
                    r = res.body().string();
                    MyUtil.showLog("httpAction success",r);
                } catch (Exception e) {
                    XToastUtils.error("HTTP返回数据获取失败 "+e.getMessage(), Toast.LENGTH_LONG);
                    e.printStackTrace();
                }
                JSONObject rObj = new JSONObject(r);
                String rCode = rObj.get("code").toString();
                String rMsg = rObj.get("msg").toString();
                if (rCode.equals("10000")) {
                    String dStr = rObj.get("data").toString();
                    JSONArray data = new JSONArray(MyUtil.isNull(dStr)?"[]":dStr);
                    runOnUiThread(() -> {
                        if (flag.equals("create_device")) devCreateDone(data);
                    });
                } else {
                    runOnUiThread(() -> {
                        XToastUtils.error(rMsg, Toast.LENGTH_LONG);
                    });
                }
            } catch (JSONException e) {
                runOnUiThread(() -> {
                    XToastUtils.error("查询失败 "+e.getMessage(), Toast.LENGTH_LONG);
                });
                e.printStackTrace();
            }
        } else {
            runOnUiThread(() -> {
                XToastUtils.error("查询失败 "+res.code(), Toast.LENGTH_LONG);
            });
        }
    }
}